package com.slipper.system.codeless.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.google.gson.reflect.TypeToken;
import com.slipper.core.cache.CacheKey;
import com.slipper.core.cache.CacheUtil;
import com.slipper.core.message.MessageUtil;
import com.slipper.core.message.Topic;
import com.slipper.system.codeless.bo.PageButtonBO;
import com.slipper.system.codeless.dao.PageButtonDao;
import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.List;


@Service
@ReadTransactional
public class PageButtonService {
    @Resource
    private PageButtonDao pageButtonDao;
    
    public PageButtonBO queryBy(String id) {
        return pageButtonDao.queryBy(id);
    }
    
    public List<PageButtonBO> queryList(PageButtonBO bo) {
        return pageButtonDao.queryList(bo);
    }
    
    public PageInfo<PageButtonBO> queryPage(PageButtonBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(pageButtonDao.queryList(bo));
    }

    public List<PageButtonBO> queryAll() {
        List<PageButtonBO> pageButtonList = CacheUtil.get(
                CacheKey.PageButton.KEY,
                new TypeToken<List<PageButtonBO>>(){}.getType());
        if (pageButtonList == null) {
            pageButtonList = pageButtonDao.queryList(new PageButtonBO());
            CacheUtil.set(CacheKey.PageButton.KEY, pageButtonList, 60 * 60);
        }
        return pageButtonList;
    }
    
    @WriteTransactional
    public int save(PageButtonBO bo) {
        int result;
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            result = pageButtonDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            result = pageButtonDao.insert(bo);
        }

        CacheUtil.remove(CacheKey.PageButton.KEY);
        MessageUtil.publish(Topic.PAGE_BUTTON_CHANGE);

        return result;
    }
    
    @WriteTransactional
    public int delete(PageButtonBO bo) {
        int result = pageButtonDao.delete(bo);
        CacheUtil.remove(CacheKey.PageButton.KEY);
        return result;
    }
}
